//
//  MeatMarketsViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/7/15.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "MeatBuyViewController.h"

#import "MeatBuySectionView.h"

#import "MeatMarketsTableViewCell.h"
#import "MeatMarketCrossTableViewCell.h"
#import "MeatMarketsBannerTableViewCell.h"

#import "MeatMarketApi.h"
#import "MeatMainScreeningBox.h"

#import "TribeRangeViewController.h"
#import "MeatShopViewController.h"
#import "MeatShopListViewController.h"
#import "MeatCartViewController.h"
#import "MeatComplaintViewConroller.h"
#import "MeatOrderViewController.h"
#import "MeatPriceViewController.h"
#import "MeatSearchShopViewController.h"

#import "MeatMapViewController.h"


@interface MeatBuyViewController ()<UIScrollViewDelegate>

@property (nonatomic, assign) BOOL isSwitchShopType;

@property (nonatomic, strong) MeatMarketApi *meatApi;
@property (nonatomic, strong) BuyMeatadvertiseListModel *bannerModel;
@property (nonatomic, strong) BuyMeatListModel *listModel;
@property (nonatomic, strong) BuyMeatPartListModel *menuListModel;


@property (nonatomic, strong) UIView *customView;
@property (nonatomic, strong) UIImageView *customIcon;

@property (nonatomic, strong) UIView *priceView;
@property (nonatomic, strong) UIImageView *priceIcon;

@property (nonatomic, strong) NSArray <BuyMeatadvertiseListModel *>*aimsArray;

@end

@implementation MeatBuyViewController

#pragma mark - view life cycle

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}


#pragma mark - init method

- (void)setupUI{
    
    [self initView];
    [self initData];
}


- (void)initView {
    
    self.isSwitchShopType = NO;
    
    [self.view addSubview:self.customView];
    [self.view addSubview:self.priceView];
}


- (void)setupLayout{
    
}

- (void)initData {
    
    [self requestBuyMeatAdvertiseData];
    [self requestBuyMeatPartDataWithType:@1];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@1 forKey:@"page"];
    [dic setObject:@10 forKey:@"limit"];
    [dic setObject:@2 forKey:@"tribeId"];
    [self requestBuyMeatShoppingListDataWithDict:dic];
}


#pragma mark - private method
//肉市-卖肉-广告
- (void)requestBuyMeatAdvertiseData {
    
    @weakify(self);
    [[self.meatApi getBuyMeatAdvertiseListData] subscribeNext:^(BuyMeatadvertiseListModel * _Nullable bannerModel) {
        
        @strongify(self);
        self.bannerModel = [[BuyMeatadvertiseListModel alloc] init];
        self.bannerModel = bannerModel;
        [self.tableView reloadData];
        
    }error:^(NSError * _Nullable error) {
        
        @strongify(self);
        [self handlingError:error];
    }];
}

//肉市-卖肉-部位信息
- (void)requestBuyMeatPartDataWithType:(NSNumber *)type{
    
    @weakify(self);
    [[self.meatApi getBuyMeatPartListDataWithType:type] subscribeNext:^(BuyMeatPartListModel * _Nullable menuListModel) {
        
        @strongify(self);
        self.menuListModel = [[BuyMeatPartListModel alloc] init];
        self.menuListModel = menuListModel;
        [self.tableView reloadData];

    }error:^(NSError * _Nullable error) {
        
        @strongify(self);
        [self handlingError:error];
    }];
}

//肉市-卖肉-店铺信息
- (void)requestBuyMeatShoppingListDataWithDict:(NSMutableDictionary *)dict{
    
    @weakify(self);
    [[self.meatApi getBuyMeatShoppingListDataWithDict:dict] subscribeNext:^(BuyMeatListModel * _Nullable listModel) {
        
        self.listModel = [[BuyMeatListModel alloc] init];
        self.listModel = listModel;
        [self.tableView reloadData];
        
    }error:^(NSError * _Nullable error) {
        
        @strongify(self);
        [self handlingError:error];
    }];
}

#pragma mark - target action

#pragma mark - private method

- (void)scrollTableViewTop{
    kWeakSelf(self);
    NSIndexPath *ip = [NSIndexPath indexPathForRow:0 inSection:1];
    [weakself.tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

#pragma mark - scrollview delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//
//    if ([scrollView isEqual:self.rightTableView] && self.isInSelectedAnimationDuration == NO) {
//
//        NSInteger section = [self.rightTableView indexPathForCell:self.rightTableView.visibleCells.firstObject].section;
//        if (self.currentLeftSideSectionValue != section) {
//
//            self.currentLeftSideSectionValue = section;
//            NSInteger newSelectedIndex = section;
//
//            [self.leftTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:newSelectedIndex inSection:0]
//                                      atScrollPosition:UITableViewScrollPositionMiddle
//                                              animated:YES];
//            [self.leftTableView reloadData];
//        }
//    }
    
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
//    if ([scrollView isEqual:self.rightTableView]) {
//        self.isInSelectedAnimationDuration = NO;
//    }
}


- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    
//    if ([scrollView isEqual:self.rightTableView]) {
//        self.isInSelectedAnimationDuration = NO;
//    }
}



#pragma mark - tableview delegate/dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSInteger num = self.listModel.page.list.count;
    NSInteger crossRow = num %2 == 0? num/2 :(num/2 +1);
    NSInteger rows = self.isSwitchShopType ?crossRow :num;
    return section == 0 ? 1 : rows;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return 0;
    }
    return [self fitSize:37];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    MeatBuySectionView *sectionView = [[MeatBuySectionView alloc] init];
    
    kWeakSelf(self);
    //购物车Block
    sectionView.dealJumpCartBlock = ^{
        
        [weakself.navigationController pushViewController:[[MeatCartViewController alloc] init] animated:YES];
        //[weakself.navigationController pushViewController:[[MeatSearchShopViewController alloc] init] animated:YES];

    };
    
    //切换店铺样式BLock
    sectionView.dealSwitchShopStyleBlock = ^{
        
        //[weakself scrollTableViewTop];
        weakself.isSwitchShopType = weakself.isSwitchShopType ?NO :YES;
        
        [UIView transitionWithView: self.tableView
                          duration: 0.35f
                           options: UIViewAnimationOptionTransitionCrossDissolve
                        animations: ^(void)
         {
             [weakself.tableView reloadData];
         }
                        completion: ^(BOOL isFinished)
         {
             /* TODO: Whatever you want here */
         }];
    };
    
    //筛选条件Block
    sectionView.dealScreeningBlock = ^(UIButton *btn) {
        
        [weakself scrollTableViewTop];
        MeatMainScreeningBox *box = [[MeatMainScreeningBox alloc] init];
        [box showView];
    };
    
    return sectionView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat listHeight = self.isSwitchShopType? 277 : 140;
    CGFloat bannerHeight = self.menuListModel.position.count >5 ? 371 : 281;
    return indexPath.section == 0 ?bannerHeight : listHeight;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        MeatMarketsBannerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatMarketsBannerTableViewCell"];
        cell.list = self.bannerModel.list;
        cell.pigPartsArray = self.menuListModel.position;
        cell.backgroundColor = mBackgroudColor;
        
        //轮播图BLock
        @weakify(self);
        cell.dealBannerBlock = ^(NSInteger params) {
            
            @strongify(self);
            MeatMapViewController *vc = [[MeatMapViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            
        };
        
        
        //猪部位ItemBlock
        cell.dealItemBlock = ^(NSInteger params) {
            @strongify(self);
            MeatSearchShopViewController *vc = [[MeatSearchShopViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            
        };
        
        return cell;
    }
    
    
    if (self.isSwitchShopType) {
        MeatMarketCrossTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatMarketCrossTableViewCell"];
        NSInteger num = indexPath.row *2;
        BuyMeatModel *model1 = self.listModel.page.list[num];
        BuyMeatModel *model2 = self.listModel.page.list[num +1];
        cell.meatModel1 = model1;
        cell.meatModel2 = model2;
        return cell;
        
    }else{
        MeatMarketsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatmarketsTableViewCell"];
        BuyMeatModel *model = self.listModel.page.list[indexPath.row];
        cell.meatModel = model;
        return cell;
    }
    
    
    return [UITableViewCell new];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MeatShopListViewController *vc = [[MeatShopListViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

    
#pragma mark - getter and setter

- (MeatMarketApi *)meatApi{
    
    if(!_meatApi){
        _meatApi = [[MeatMarketApi alloc]init];
    }
    return _meatApi;
}


- (UIView *)customView{
    
    if (!_customView) {
        _customView = [[UIView alloc] init];
        _customView.size = CGSizeMake(80, 60);
        _customView.mj_y = 200;
        _customView.mj_x = KScreenWidth - 80;
        _customView.tag = 300;
        
        [_customView addSubview:self.customIcon];
        
        
        @weakify(self);
        _customView.tapBlock = ^{
            @strongify(self);
            
            if (self.customView.tag == 300) {
                self.customView.tag = -300;
                
                [self setAnimationByX:-40 transferX:-M_PI/4 transferY:0 isJump:YES layer:self.customIcon.layer];
            }else{
                
                NSLog(@"________________22222222");
                self.customView.tag = 300;
                [self setAnimationByX:10 transferX:0 transferY:-M_PI/4 isJump:NO layer:self.customIcon.layer];
            }
        };
    }
    return _customView;
}



- (UIImageView *)customIcon{
    
    if (!_customIcon) {
        _customIcon = [UIImageView makeImageByImageName:@"meat_buy_customerservice" cornerRadius:0];
        _customIcon.size = CGSizeMake(60, 60);
        _customIcon.mj_x =  70 - _customIcon.width/2.0;
        _customIcon.mj_y = 0;
        CGAffineTransform at = CGAffineTransformMakeRotation(-M_PI/4);
        [_customIcon setTransform:at];
        
    }
    return _customIcon;
}


- (void)setAnimationByX:(CGFloat)x transferX:(CGFloat)from transferY:(CGFloat)to isJump:(BOOL)jump layer:(CALayer *)layer{
    
    CABasicAnimation *animation1 = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
    animation1.toValue = @(x);
    
    CABasicAnimation *animation2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation2.fromValue = [NSNumber numberWithFloat: from];
    animation2.toValue = [NSNumber numberWithFloat:to];
    
    if (jump) {
    
        CAAnimationGroup *group = [CAAnimationGroup animation];
        group.duration = 0.8;
        group.repeatCount = 1;
        group.autoreverses = NO; //默认就是NO，设置成Yes之后下面fillMode就不起作用了
        group.fillMode = kCAFillModeForwards;
        group.removedOnCompletion = NO;
        group.animations = [NSArray arrayWithObjects:animation1, animation2, nil];
        [layer addAnimation:group forKey:@"group"];
    }else{
        
        CAAnimationGroup *group = [CAAnimationGroup animation];
        group.duration = 0.4;
        group.repeatCount = 1;
        group.autoreverses = NO; //默认就是NO，设置成Yes之后下面fillMode就不起作用了
        group.fillMode = kCAFillModeForwards;
        group.removedOnCompletion = NO;
        group.animations = [NSArray arrayWithObjects:animation1, animation2, nil];
        [layer addAnimation:group forKey:@"group"];
    }
    
    if (jump) {
        
        CAKeyframeAnimation *animation = [CABasicAnimation makeGravityJumpAnimation];
        [layer addAnimation:animation forKey:nil];
    }
}


- (UIView *)priceView{
    
    if (!_priceView) {
        _priceView = [[UIView alloc] init];
        _priceView.size = CGSizeMake(80, 60);
        _priceView.mj_y = 324;
        _priceView.mj_x = KScreenWidth - 80;
        _priceView.tag = 400;
        
        [_priceView addSubview:self.priceIcon];
        
        
        @weakify(self);
        _priceView.tapBlock = ^{
            @strongify(self);
            
            if (self.priceView.tag == 400) {
                self.priceView.tag = -400;
                NSLog(@"________________111111111");
                
                [self setAnimationByX:-40 transferX:-M_PI/4 transferY:0 isJump:YES layer:self.priceIcon.layer];
            }else{
                
                NSLog(@"________________22222222");
                self.priceView.tag = 400;
                [self setAnimationByX:10 transferX:0 transferY:-M_PI/4 isJump:NO layer:self.priceIcon.layer];
            }
        };
    }
    
    return _priceView;
}


- (UIImageView *)priceIcon{
    
    if (!_priceIcon) {
        _priceIcon = [UIImageView new];
        _priceIcon.image = [UIImage imageNamed:@"meat_buy_orange"];
        _priceIcon.size = CGSizeMake(60, 60);
        _priceIcon.mj_x = 70- _priceIcon.width /2.0;
        _priceIcon.mj_y = 0;
        
        CGAffineTransform at = CGAffineTransformMakeRotation(-M_PI/4);
        [_priceIcon setTransform:at];
    }
    return _priceIcon;
}


#pragma mark - override methods

- (void)registerTableViewCell{
    
    CGFloat kTableViewHeight = KScreenHeight - 192 - TJ_TabBarHeight;
    self.tableView.height = kTableViewHeight;
    [self.tableView registerClass:[MeatMarketsBannerTableViewCell class] forCellReuseIdentifier:@"MeatMarketsBannerTableViewCell"];
    [self.tableView registerClass:[MeatMarketsTableViewCell class] forCellReuseIdentifier:@"MeatmarketsTableViewCell"];
    [self.tableView registerClass:[MeatMarketCrossTableViewCell class] forCellReuseIdentifier:@"MeatMarketCrossTableViewCell"];
}


@end
